package com.jintoufs.web.action;

import com.jintoufs.domain.user.User;
import com.jintoufs.service.user.UserService;
import com.jintoufs.web.action.shiro.IncorrectCaptchaException;
import com.jintoufs.web.action.shiro.UnModifyDefaultPasswordException;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.SupportAction;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * 包括登陆、注册、忘记密码等前台Action
 *
 * @author tcq
 */
@Controller
public class IndexAction extends SupportAction {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login")
    public String showLoginForm(HttpServletRequest req, Model model) {
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        String username = getString(req, "username");
        String error = null;
        boolean modified = true;
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户不存在";
        } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
            error = "无权限访问该目录";
        } else if (IncorrectCaptchaException.class.getName().equals(exceptionClassName)) {
            error = "验证码错误";
        } else if (UnModifyDefaultPasswordException.class.getName().equals(exceptionClassName)) {
            modified = false;
        } else if (exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }

        model.addAttribute("username", username);
        model.addAttribute("error", error);
        model.addAttribute("modified", modified);
        if (req.getParameter("forceLogout") != null) {
            model.addAttribute("error", "您已经被管理员强制退出，请重新登录");
        }
        return "/login";
    }


    @RequestMapping("dashboard")
    public String dashboard(Byte isLogin, @CurrentUser User user) throws IOException {
        if (isLogin == null || isLogin != 0) {
            user.setLastLoginTime(new Date());
            userService.update(user);
        }
        return "/dashboard";
    }

}